<template>
	<div class="dynamic-qrcode-view" :style="boxStyle" ref="view" v-resize="onResize">
		<img
			class="bg_img"
			v-if="options.bg_img"
			ref="bgImg"
			:src="options.bg_img"
			v-long-touch="onCopy"
			@load="onBgLoad"
		/>
		<img
			class="qrcode"
			v-if="qrcode && bgload && options.bg_img"
			:src="qrcode"
			:style="qrcodeStyle"
			v-long-touch="onCopy"
			@click="handleClick"
		/>
		<long-touch-wechat
			v-else-if="qrcode && bgload"
			image
			image-autosize
			margin="0"
			:qrcode="qrcode"
			:desc="config.wechat_dialog_desc"
			@callback="onCopy"
		/>
	</div>
</template>
<script>
import tpl from '@/mixins/tpl'
import resize from '@/directives/resize'
import LongTouchWechat from '@/components/long-touch-wechat'
import longTouch from '@/directives/long-touch'

export default {
	name: 'dynamic-qrcode-view',
	components: {
		LongTouchWechat,
	},
	mixins: [tpl],
	directives: {
		longTouch,
		resize,
	},
	props: {
		view: {
			type: Object,
			default: () => ({}),
		},
	},
	data() {
		return {
			mpScheme: '',
			fontSize: 16,
			winW: 375,
			bgH: 375,
			bgload: false,
		}
	},
	computed: {
		options() {
			return this.view.options
		},
		qrcode() {
			return [4, 5].includes(this.customer.contact_type * 1) ? this.customer.image_url : ''
		},
		boxStyle() {
			const { bg_img } = this.options
			if (!bg_img) {
				return {
					// height: this.winW + 'px',
					height: 'auto',
				}
			}
			return null
		},
		qrcodeStyle() {
			const { size, top, left, bg_height, bg_img } = this.options
			if (!bg_img) {
				// 当没有背景图片时
				return {
					width: '100%',
					height: 'auto',
					position: 'relative',
					// left: 0,
					// top: 0,
				}
			}

			let ratioW = this.winW / 375
			let ratioH = this.bgH / bg_height
			// console.log({ ratioW, ratioH });
			let leftV = left * ratioW
			let topV = top * ratioH
			return {
				width: size * ratioW + 'px',
				height: size * ratioW + 'px',
				left: leftV + 'px',
				top: topV + 'px',
			}
		},
	},
	mounted() {
		const { bg_img } = this.options
		if (!bg_img) {
			this.onBgLoad()
		}
	},
	methods: {
		onResize() {
			let fontSize = this.getStyle(document.documentElement, 'font-size')
			this.fontSize = Number(fontSize.replace('px', ''))

			let width = this.$refs?.view?.clientWidth ?? 375
			this.winW = width
			this.onBgLoad()
		},
		onBgLoad() {
			this.$nextTick(() => {
				let bgH = this.$refs?.bgImg?.height || this.winW
				this.bgH = bgH
				setTimeout(() => {
					this.bgload = true
				}, 50)
			})
		},
		async handleClick(ev) {
			if (!this.qrcode) return
			this.$emit('click', ev)
		},
		onCopy() {
			this.$emit('copywx')
		},
	},
}
</script>
<style lang="scss" scoped>
.dynamic-qrcode-view {
	position: relative;
	img {
		width: 100%;
		vertical-align: middle;
	}
	.qrcode {
		width: 125px;
		height: 125px;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 10;
	}
}
</style>
